<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="随着多核处理器的出现，提升应用程序处理速度最有效的方式是编写能充分发挥多核能力的软件。可以通过切分大型的任务，让每个子任务并行运行，在Java中目前有直接使用线程的方式、使用Fork/Join框架和JDK8中的并行流来达到这一目的。 这段代码演示了分段求和用线程方式的实现。 分别开启2个线程，给予不同范围的数值进行求和，最后调用join()方法等到线程执行完毕，将2个线程的结果相加得到结果。">
<meta name="keywords" content="java,jdk8">
<meta property="og:type" content="article">
<meta property="og:title" content="JDK8-Fork&#x2F;Join和CompletableFuture的使用">
<meta property="og:url" content="http://www.saily.top/2017/09/28/jdk8-11/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="随着多核处理器的出现，提升应用程序处理速度最有效的方式是编写能充分发挥多核能力的软件。可以通过切分大型的任务，让每个子任务并行运行，在Java中目前有直接使用线程的方式、使用Fork/Join框架和JDK8中的并行流来达到这一目的。 这段代码演示了分段求和用线程方式的实现。 分别开启2个线程，给予不同范围的数值进行求和，最后调用join()方法等到线程执行完毕，将2个线程的结果相加得到结果。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-09-28T08:39:48.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JDK8-Fork&#x2F;Join和CompletableFuture的使用">
<meta name="twitter:description" content="随着多核处理器的出现，提升应用程序处理速度最有效的方式是编写能充分发挥多核能力的软件。可以通过切分大型的任务，让每个子任务并行运行，在Java中目前有直接使用线程的方式、使用Fork/Join框架和JDK8中的并行流来达到这一目的。 这段代码演示了分段求和用线程方式的实现。 分别开启2个线程，给予不同范围的数值进行求和，最后调用join()方法等到线程执行完毕，将2个线程的结果相加得到结果。">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2017/09/28/jdk8-11/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>JDK8-Fork/Join和CompletableFuture的使用 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2017/09/28/jdk8-11/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JDK8-Fork/Join和CompletableFuture的使用
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-28T09:14:20+08:00">9月 28 2017</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/jdk8/" itemprop="url" rel="index"><span itemprop="name">jdk8</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>随着多核处理器的出现，提升应用程序处理速度最有效的方式是编写能充分发挥多核能力的软件。可以通过切分大型的任务，让每个子任务并行运行，在Java中目前有直接使用线程的方式、使用Fork/Join框架和JDK8中的并行流来达到这一目的。</p>
<p>这段代码演示了分段求和用线程方式的实现。</p>
<p>分别开启2个线程，给予不同范围的数值进行求和，最后调用join()方法等到线程执行完毕，将2个线程的结果相加得到结果。</p>
<a id="more"></a>
<h2 id="Thread方式"><a href="#Thread方式" class="headerlink" title="Thread方式"></a>Thread方式</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Random;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadJoinTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Computer</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> start;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> end;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> result;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> []array;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Computer</span><span class="params">(<span class="keyword">int</span> []array , <span class="keyword">int</span> start , <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.array = array;</span><br><span class="line">		<span class="keyword">this</span>.start = start;</span><br><span class="line">		<span class="keyword">this</span>.end = end;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i = start; i &lt; end ; i++) &#123;</span><br><span class="line">			result += array[i];</span><br><span class="line">			<span class="keyword">if</span>(result &lt; <span class="number">0</span>) result &amp;= Integer.MAX_VALUE;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getResult</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> result;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">	</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">int</span> COUNTER = <span class="number">100000001</span>;</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String []args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> []array = <span class="keyword">new</span> <span class="keyword">int</span>[COUNTER];</span><br><span class="line">	Random random = <span class="keyword">new</span> Random();</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span> ; i &lt; COUNTER ; i++) &#123;</span><br><span class="line">		array[i] = Math.abs(random.nextInt());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">	Computer c1 = <span class="keyword">new</span> Computer(array , <span class="number">0</span> , COUNTER / <span class="number">2</span>);</span><br><span class="line">	Computer c2 = <span class="keyword">new</span> Computer(array , (COUNTER / <span class="number">2</span>) + <span class="number">1</span> , COUNTER);</span><br><span class="line">	c1.start();</span><br><span class="line">	c2.start();</span><br><span class="line">	c1.join();</span><br><span class="line">	c2.join();</span><br><span class="line">	System.out.println(System.currentTimeMillis() - start);</span><br><span class="line">	<span class="comment">//System.out.println(c1.getResult());</span></span><br><span class="line">	System.out.println((c1.getResult() + c2.getResult()) &amp; Integer.MAX_VALUE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Fork-Join"><a href="#Fork-Join" class="headerlink" title="Fork/Join"></a>Fork/Join</h2><p>关于Fork/Join框架的介绍的详细介绍，还可以查看方腾飞老师的文章<a href="http://ifeve.com/talk-concurrency-forkjoin/，介绍得非常详细。" target="_blank" rel="noopener">http://ifeve.com/talk-concurrency-forkjoin/，介绍得非常详细。</a></p>
<p>Fork/Join的实现是要继承<strong>RecursiveTask</strong>类，实现<strong>compute()</strong>方法，如例子所示，同样也是求和的计算，用继承的类，将要求和的范围传入，在<strong>compute()</strong>方法内部进行任务拆分，最后将每个任务的结果进行相加。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 继承RecursiveTask来创建可以用于fork/join框架的任务</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ForkJoinSumCalculator</span> <span class="keyword">extends</span> <span class="title">RecursiveTask</span>&lt;<span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 要求和的数组</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">long</span>[] numbers;</span><br><span class="line">    <span class="comment">// 子任务处理的数组的起始位置和终止位置</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> start;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> end;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> THRESHHOLD = <span class="number">10_100</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ForkJoinSumCalculator</span><span class="params">(<span class="keyword">long</span>[] numbers)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(numbers, <span class="number">0</span>, numbers.length);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">ForkJoinSumCalculator</span><span class="params">(<span class="keyword">long</span>[] numbers, <span class="keyword">int</span> start, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.numbers = numbers;</span><br><span class="line">        <span class="keyword">this</span>.start = start;</span><br><span class="line">        <span class="keyword">this</span>.end = end;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Long <span class="title">compute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 该任务负责求和的部分的大小</span></span><br><span class="line">        <span class="keyword">int</span> length = end - start;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 如果大小小于或等于阈值，顺序计算结果</span></span><br><span class="line">        <span class="keyword">if</span> (length &lt; THRESHHOLD) &#123;</span><br><span class="line">            <span class="keyword">return</span> computeSequentially();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建一个子任务来为数组的前一半求和</span></span><br><span class="line">        ForkJoinSumCalculator leftTask = <span class="keyword">new</span> ForkJoinSumCalculator(numbers, start, start + length / <span class="number">2</span>);</span><br><span class="line">        <span class="comment">// 利用另一个ForkJoinPool线程异步执行新创建的子任务</span></span><br><span class="line">        leftTask.fork();</span><br><span class="line">        <span class="comment">// 创建一个任务为数组的后一半求和</span></span><br><span class="line">        ForkJoinSumCalculator rightTask = <span class="keyword">new</span> ForkJoinSumCalculator(numbers, start + length / <span class="number">2</span>, end);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 同步执行第二个子任务，有可能允许进一步递归划分</span></span><br><span class="line">        Long rightResult = rightTask.compute();</span><br><span class="line">        <span class="comment">// 读取第一个子任务的结果，如果尚未完成就等待</span></span><br><span class="line">        Long leftResult = leftTask.join();</span><br><span class="line">        <span class="comment">// 该任务的结果是两个子任务结果的组合</span></span><br><span class="line">        <span class="keyword">return</span> leftResult + rightResult;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> Long <span class="title">computeSequentially</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt; end; i++) &#123;</span><br><span class="line">            sum += numbers[i];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span>[] numbers = LongStream.rangeClosed(<span class="number">1</span>, <span class="number">1000000</span>).toArray();</span><br><span class="line">        ForkJoinTask&lt;Long&gt; task = <span class="keyword">new</span> ForkJoinSumCalculator(numbers);</span><br><span class="line">        Long sum = <span class="keyword">new</span> ForkJoinPool().invoke(task);</span><br><span class="line">        System.out.println(sum);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Java8-parallelStream"><a href="#Java8-parallelStream" class="headerlink" title="Java8-parallelStream"></a>Java8-parallelStream</h2><p>Java8做这种求和的操作很简洁，一行代码就可以解决。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IntStream.rangeClosed(<span class="number">0</span>, <span class="number">100000000</span>).parallel().sum()</span><br></pre></td></tr></table></figure>
<p>之前在网上了解到说Java 8 并行流采用共享线程池，对性能造成了严重影响。可以包装流来调用自己的线程池解决性能问题。</p>
<p>如果要使用线程池，可采用以下方式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">ForkJoinPool forkJoinPool = <span class="keyword">new</span> ForkJoinPool(<span class="number">3</span>);  </span><br><span class="line">forkJoinPool.submit(() -&gt; &#123;  </span><br><span class="line">    firstRange.parallelStream().forEach((number) -&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">5</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123; &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">ForkJoinPool forkJoinPool2 = <span class="keyword">new</span> ForkJoinPool(<span class="number">3</span>);  </span><br><span class="line">forkJoinPool2.submit(() -&gt; &#123;  </span><br><span class="line">    secondRange.parallelStream().forEach((number) -&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">5</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="CompletableFuture"><a href="#CompletableFuture" class="headerlink" title="CompletableFuture"></a>CompletableFuture</h2><h3 id="Future接口"><a href="#Future接口" class="headerlink" title="Future接口"></a>Future接口</h3><p>在介绍<strong>CompletableFuture</strong>之前，必须要说一下<strong>Future</strong>接口，<strong>Future</strong>接口在Java5中被引入，它建模了一种<strong><em>异步计算</em></strong>，返回一个执行运算结果的引用，当运算结束后，这个引用被返回给调用方。这样就不需要等到方法结果，调用线程可以接着去做其他事情，这样就完成了异步调用，方法结果只能通过get()方法获取，get()方法是阻塞的，会阻塞直到异步方法运行完成返回结果。打个比方，把衣服放进洗衣机清洗，这个时候我们可以去做点别的事情，等到洗衣机清洗完成后，我们才会去取干净的衣服。下面展示一个简单的示例，只需要将操作封装到<strong>Callable</strong>接口中：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FutureTaskTest</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CallImpl</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">private</span> String input;</span><br><span class="line">		</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">CallImpl</span><span class="params">(String input)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.input = input;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> String <span class="title">call</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			<span class="keyword">try</span> &#123;<span class="comment">//延迟一点点</span></span><br><span class="line">				Random random = <span class="keyword">new</span> Random();</span><br><span class="line">				Thread.sleep((random.nextInt() + <span class="keyword">this</span>.input.hashCode()) &amp; <span class="number">10000</span>);</span><br><span class="line">			&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> <span class="string">"输入参数:"</span> + input;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String []args)</span> <span class="keyword">throws</span> InterruptedException, ExecutionException </span>&#123;</span><br><span class="line">		ExecutorService executorService = Executors.newFixedThreadPool(<span class="number">2</span>);</span><br><span class="line">		<span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">		List&lt;Future&lt;String&gt;&gt; list = Arrays.asList(</span><br><span class="line">			executorService.submit(<span class="keyword">new</span> CallImpl(<span class="string">"t1"</span>)) , </span><br><span class="line">			executorService.submit(<span class="keyword">new</span> CallImpl(<span class="string">"t2"</span>)) ,</span><br><span class="line">			executorService.submit(<span class="keyword">new</span> CallImpl(<span class="string">"t3"</span>))</span><br><span class="line">		);</span><br><span class="line">		<span class="comment">/*List&lt;Future&lt;String&gt;&gt; list = executorService.invokeAll(Arrays.asList(</span></span><br><span class="line"><span class="comment">			new CallImpl("t1"),</span></span><br><span class="line"><span class="comment">			new CallImpl("t2"),</span></span><br><span class="line"><span class="comment">			new CallImpl("t3")</span></span><br><span class="line"><span class="comment">		));*/</span></span><br><span class="line">		<span class="keyword">for</span>(Future&lt;String&gt; future : list) &#123;</span><br><span class="line">			String result = future.get();<span class="comment">//如果没返回，会阻塞</span></span><br><span class="line">			System.out.println(result + <span class="string">"\t"</span> + System.currentTimeMillis());</span><br><span class="line">		&#125;</span><br><span class="line">		executorService.shutdown();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Future接口的局限性"><a href="#Future接口的局限性" class="headerlink" title="Future接口的局限性"></a>Future接口的局限性</h3><p>Future提供了isDone()方法检测异步计算是否已经结束，get()方法等待异步操作结束，以及获取计算的结果。但是这些操作依然很难实现：<strong>等到所有Future任务完成，通知线程获取结果并合并</strong>。下面就一起来看看JDK8中新引入的<strong>CompletableFuture</strong>。</p>
<h3 id="使用CompletableFuture构建异步应用"><a href="#使用CompletableFuture构建异步应用" class="headerlink" title="使用CompletableFuture构建异步应用"></a>使用CompletableFuture构建异步应用</h3><p><strong>CompletableFuture</strong>实现了<strong>Future</strong>接口，它的<strong>complete()</strong>方法就相当于结束<strong>CompletableFuture</strong>对象的执行，并设置变量的值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yangfan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/04/11</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Shop</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Random random = <span class="keyword">new</span> Random();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Shop</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPrice</span><span class="params">(String product)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> price =  calculatePrice(product);</span><br><span class="line">        Discount.Code code = Discount.Code.values()[random.nextInt(Discount.Code.values().length)];</span><br><span class="line">        <span class="keyword">return</span> String.format(<span class="string">"%s:%.2f:%s"</span>, name, price, code);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Future&lt;Double&gt; <span class="title">getPriceAsync1</span><span class="params">(String product)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 创建CompletableFuture对象，它会包含计算的结果</span></span><br><span class="line">        CompletableFuture&lt;Double&gt; futurePrice = <span class="keyword">new</span> CompletableFuture&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 在另一个线程中以异步方式执行计算</span></span><br><span class="line">        <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">double</span> price = calculatePrice(product);</span><br><span class="line">                <span class="comment">//  需长时间计算的任务结束并得出结果时，设置Future的返回值</span></span><br><span class="line">                futurePrice.complete(price);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                <span class="comment">//异常处理</span></span><br><span class="line">                futurePrice.completeExceptionally(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 无需等待还没结束的计算，直接返回Future对象</span></span><br><span class="line">        <span class="keyword">return</span> futurePrice;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Future&lt;Double&gt; <span class="title">getPriceAsync</span><span class="params">(String product)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> CompletableFuture.supplyAsync(() -&gt; calculatePrice(product));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">double</span> <span class="title">calculatePrice</span><span class="params">(String product)</span> </span>&#123;</span><br><span class="line">        randomDelay();</span><br><span class="line">        <span class="keyword">return</span> random.nextDouble() * product.charAt(<span class="number">0</span>) + product.charAt(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">delay</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000L</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">randomDelay</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> delay = <span class="number">500</span> + random.nextInt(<span class="number">2000</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(delay);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Shop shop = <span class="keyword">new</span> Shop(<span class="string">"BestShop"</span>);</span><br><span class="line">        <span class="keyword">long</span> start = System.nanoTime();</span><br><span class="line">        <span class="comment">// 查询商店，试图去的商品的价格</span></span><br><span class="line">        Future&lt;Double&gt; futurePrice = shop.getPriceAsync(<span class="string">"my favorte product"</span>);</span><br><span class="line">        <span class="keyword">long</span> invocationTime = (System.nanoTime() - start) / <span class="number">1_000_000</span>;</span><br><span class="line">        System.out.println(<span class="string">"Invocation returned after "</span> + invocationTime + <span class="string">" msecs"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 执行更多任务，比如查询其他商店</span></span><br><span class="line">        <span class="comment">//doSomethingElse();</span></span><br><span class="line">        <span class="comment">// 在计算商品价格的同时</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 从Future对象中读取价格，如果价格未知，会发生阻塞</span></span><br><span class="line">            <span class="keyword">double</span> price = futurePrice.get();</span><br><span class="line">            System.out.printf(<span class="string">"Price is %.2f%n"</span>, price);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException | ExecutionException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> retrievalTime = ((System.nanoTime() - start) / <span class="number">1_000_000</span>);</span><br><span class="line">        System.out.println(<span class="string">"Price returned after "</span> + retrievalTime + <span class="string">" msecs"</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的例子来自于《Java8实战》，模拟了一个耗时的操作，然后通过<strong>CompletableFuture</strong>包装成异步方法进行调用。注意代码里演示了两种方式，一种自己new一个线程再调用complete方法，还有就是用<strong>CompletableFuture</strong>自身提供的工厂方法，<strong>CompletableFuture.supplyAsync</strong>，它能更容易地完成整个流程，还不用担心实现的细节。</p>
<p>现在看来好像和<strong>Future</strong>方式也没有什么区别，都是包装一下最后通过<strong>get()</strong>方法获取结果，但是<strong>CompletableFuture</strong>配合Java8用起来就非常厉害了，它提供了很多方便的方法，下面进行一个演示。</p>
<p>同样是价格查询，我们现在接到一个需求，就是获取一个商品在不同商店的报价，一般来说用传统的方式就是写一个<code>for</code>循环，遍历商店然后获取价格，要想效率快一点我们也可以用并行流的方式来查询，但是并行流返回的结果是无序的。下面再将异步也引入，我们可以实现有序的并行操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> List&lt;String&gt; <span class="title">findPrices_1</span><span class="params">(String product)</span> </span>&#123;</span><br><span class="line">    List&lt;CompletableFuture&lt;String&gt;&gt; priceFutures = shops.stream()</span><br><span class="line">            .map(shop -&gt; CompletableFuture.supplyAsync(() -&gt; shop.getName() + <span class="string">" price is "</span> + shop.getPrice(product), executor)).collect(Collectors.toList());</span><br><span class="line">    <span class="keyword">return</span> priceFutures.stream().map(CompletableFuture::join).collect(Collectors.toList());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里创建<strong>CompletableFuture</strong>和调用<strong>join()</strong>方法是两个不同的流是有原因的，如果只在一个流里，那么就没有异步的效果了，下一个Future必须等到上一个完成后才会被创建和执行。上面的代码执行效率并不会比并行流的效率差。</p>
<p>默认情况下，并行流和CompletableFuture默认都是用固定数目的线程，都是取决于<strong>Runtime. getRuntime().availableProcessors()</strong>的返回值。并行流的线程池并不好控制，其本质是内部隐含使用了ForkJoinPool线程池，最大并发数可以通过系统变量设置。所以<strong>CompletableFuture</strong>也就具有了优势，它允许配置自定义的线程池，这也可以为实际应用程序带来性能上的提升（并行流无法提供的API），<strong>CompletableFuture.supplyAsync(Supplier supplier,Executor executor)</strong>提供了重载的方法来指定执行器使用自定义的线程池。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建一个线程池，线程池中线程的数目为100和商店数目二者中较小的一个值</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Executor executor = Executors.newFixedThreadPool(Math.min(shops.size(), <span class="number">100</span>), <span class="keyword">new</span> ThreadFactory() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Thread <span class="title">newThread</span><span class="params">(Runnable r)</span> </span>&#123;</span><br><span class="line">        Thread t = <span class="keyword">new</span> Thread(r);</span><br><span class="line">        <span class="comment">// 使用守护线程---这种方式不会阻止程序关掉</span></span><br><span class="line">        t.setDaemon(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> t;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="并行–使用流还是CompletableFutures？"><a href="#并行–使用流还是CompletableFutures？" class="headerlink" title="并行–使用流还是CompletableFutures？"></a>并行–使用流还是CompletableFutures？</h3><p>现在我们知道对集合进行并行计算有两种方式：</p>
<ol>
<li>转化为并行流，利用map开展工作。</li>
<li>取出每一个元素，创建线程，在<strong>CompletableFuture</strong>内对其进行操作</li>
</ol>
<p>后者提供了更多的灵活性，你可以调整线程池的大小，而这能帮助我们确保整体的计算不会因为线程都在等待I/O而发生阻塞。</p>
<p>那么如何选择呢，建议如下：</p>
<ul>
<li>进行计算密集型的操作，并且没有I/O，那么推荐使用Stream接口，因为实现简单，同时效率也可能是最高的（如果所有的线程都是计算密集型的，那就没有必要创建比处理器核数更多的线程）。</li>
<li>如果并行操作设计等到I/O的操作（网络连接，请求等），那么使用<strong>CompletableFuture</strong>灵活性更好，通过控制线程数量来优化程序的运行。</li>
</ul>
<p>CompletableFuture还提供了了一些非常有用的操作例如，thenApply(),thenCompose(),thenCombine()等</p>
<ul>
<li>thenApply()是操作完成后将结果传入进行转换</li>
<li>thenCompose()是对两个异步操作进行串联，第一个操作完成时，对第一个<strong>CompletableFuture</strong>对象调用thenCompose，并向其传递一个函数。当第一个<strong>CompletableFuture</strong>执行完毕后，它的结果将作为该函数的参数，这个函数的返回值是以第一个<strong>CompletableFuture</strong>的返回做输入计算出第二个<strong>CompletableFuture</strong>对象。</li>
<li>thenCombine()会异步执行两个<strong>CompletableFuture</strong>任务，然后等待它们计算出结果后再进行计算。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> List&lt;String&gt; <span class="title">findPrices</span><span class="params">(String product)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    List&lt;CompletableFuture&lt;String&gt;&gt; priceFutures = shops.stream()</span><br><span class="line">            <span class="comment">// 以异步方式取得每个shop中指定产品的原始价格</span></span><br><span class="line">            .map(shop -&gt; CompletableFuture.supplyAsync(() -&gt; shop.getPrice(product), executor))</span><br><span class="line">            <span class="comment">// Quote对象存在时，对其返回值进行转换</span></span><br><span class="line">            .map(future -&gt; future.thenApply(Quote::parse))</span><br><span class="line">            <span class="comment">// 使用另一个异步任务构造期望的Future，申请折扣</span></span><br><span class="line">            .map(future -&gt; future.thenCompose(quote -&gt; CompletableFuture.supplyAsync(() -&gt; Discount.applyDiscount(quote), executor)))</span><br><span class="line">            .collect(Collectors.toList());</span><br><span class="line">    <span class="keyword">return</span> priceFutures.stream().map(CompletableFuture::join).collect(Collectors.toList());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通常而言，名称中不带Async的方法和它的前一个任务一样，在同一个线程中运行；而名称以Async结尾的方法会将后续的任务提交到一个线程池，所以每个任务都是由不同线程处理的，例如thenApplyAsync()，thenComposeAsync()等。</p>
<p>最后看一段利用<strong>thenAccept()</strong>来使用异步计算结果的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这里演示获取最先返回的数据</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Stream&lt;CompletableFuture&lt;String&gt;&gt; findPricesStream(String product) &#123;</span><br><span class="line">    <span class="keyword">return</span> shops.stream().map(shop -&gt; CompletableFuture.supplyAsync(() -&gt; shop.getPrice(product), executor))</span><br><span class="line">            .map(future -&gt; future.thenApply(Quote::parse))</span><br><span class="line">            .map(future -&gt; future.thenCompose(quote -&gt; CompletableFuture.supplyAsync(</span><br><span class="line">                    () -&gt; Discount.applyDiscount(quote), executor)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">long</span> start = System.nanoTime();</span><br><span class="line"><span class="comment">//        System.out.println(findPrices("myPhone27S"));</span></span><br><span class="line">    CompletableFuture[] futures = findPricesStream(<span class="string">"myPhone27S"</span>)</span><br><span class="line">            .map(f -&gt; f.thenAccept(s -&gt; System.out.println(s + <span class="string">" (done in "</span> +</span><br><span class="line">                    ((System.nanoTime() - start) / <span class="number">1_000_000</span>) + <span class="string">" msecs)"</span>)))</span><br><span class="line">            .toArray(CompletableFuture[]::<span class="keyword">new</span>);</span><br><span class="line"><span class="comment">//        CompletableFuture.allOf(futures).join();</span></span><br><span class="line">    CompletableFuture.anyOf(futures).join();</span><br><span class="line">    <span class="keyword">long</span> duration = (System.nanoTime() - start) / <span class="number">1_000_000</span>;</span><br><span class="line">    System.out.println(<span class="string">"Done in "</span> + duration + <span class="string">" msecs"</span>);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样就几乎无需等待<strong>findPricesStream</strong>的调用，实现了一个真正的异步方法。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/jdk8/" rel="tag"># jdk8</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/22/netty7/" rel="next" title="Netty-源码分析(二)">
                <i class="fa fa-chevron-left"></i> Netty-源码分析(二)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/28/git3/" rel="prev" title="Git-checkout、stash等命令">
                Git-checkout、stash等命令 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Thread方式"><span class="nav-number">1.</span> <span class="nav-text">Thread方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Fork-Join"><span class="nav-number">2.</span> <span class="nav-text">Fork/Join</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java8-parallelStream"><span class="nav-number">3.</span> <span class="nav-text">Java8-parallelStream</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CompletableFuture"><span class="nav-number">4.</span> <span class="nav-text">CompletableFuture</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Future接口"><span class="nav-number">4.1.</span> <span class="nav-text">Future接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Future接口的局限性"><span class="nav-number">4.2.</span> <span class="nav-text">Future接口的局限性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用CompletableFuture构建异步应用"><span class="nav-number">4.3.</span> <span class="nav-text">使用CompletableFuture构建异步应用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#并行–使用流还是CompletableFutures？"><span class="nav-number">4.4.</span> <span class="nav-text">并行–使用流还是CompletableFutures？</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
